<template>
  <div class="iframe-container" v-loading="loading">
    <iframe
      :src="src"
      ref="iframeCont"
      id="_iframe"
      @load="loaded"
      name="_iframe"
      frameborder="0"
      width="100%"
      height="100%"></iframe>
  </div>
</template>

<script>
// import bus from '@/api/bus'
export default {
  props: {
    checkUrl: {
      type: String,
      default: ''
    },
    iframeConfig: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      src: '',
      iframeWin: null,
      loading: true,
      postMsgData: null,
      originUrl: null
    }
  },
  created() {
    this.loading = true
    this.src = this.checkUrl
    window.removeEventListener('message', this.emitIframePMBackEvent)
    window.addEventListener('message', this.emitIframePMBackEvent, false)
  },
  mounted() {
    this.$nextTick(() => {
      this.iframeWin = this.$refs.iframeCont.contentWindow
      this.iframeWin && this.iframeWin.postMessage({ type: 'firstConfig', data: { ...this.iframeConfig, yijiToken: this.$store.getters.token }}, '*')
    }, 200)
  },
  beforeDestroy() {
    window.removeEventListener('message', this.emitIframePMBackEvent)
  },
  methods: {
    emitIframePMBackEvent(event) {
      // console.log('临床预约回调')
      this.$emit('iframePMBack', event.data)
    },
    loaded() {
      // console.log('iframe loaded!!!', this.postMsgData)
      this.$nextTick(() => {
        if (this.loading) {
          this.loading = false
          this.iframeWin && this.iframeWin.postMessage({ type: 'firstConfig', data: { ...this.iframeConfig, yijiToken: this.$store.getters.token }}, '*')
        }
        if (this.postMsgData) {
          this.iframeWin && this.iframeWin.postMessage(this.postMsgData || this.iframeConfig, this.originUrl)
          this.postMsgData = null
        }
      })
    },
    postMsg(data, originUrl) {
      console.warn('postMsg data', data)
      data.reservedNumUserDeptName = this.$store.state.user.deptName
      if (data.type === 'changeAppointmentTypeConfig' && data.isNoRowCurr) {
        // 获取当前 URL
        let currentUrl = new URL(this.src)
        // 获取 URL 的查询参数部分，并进行解析
        let searchParams = new URLSearchParams(currentUrl.search)
        // 修改指定参数的值
        searchParams.set('appointmentType2', data.data.typeConfig)
        // console.error('data.data.typeConfig', data.data.typeConfig)
        // 将修改后的查询参数部分拼接回原 URL 中，并更新 this.src
        currentUrl.search = '?' + searchParams.toString()
        this.src = currentUrl.href
      }
      console.log('this.loading ', this.loading)
      if (!this.loading) {
        this.iframeWin && this.iframeWin.postMessage(data, originUrl)
        // console.log('postMsg originUrl', this.originUrl)
      } else {
        this.postMsgData = data
        this.originUrl = originUrl
        // console.log('postMsg originUrl', this.originUrl)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.iframe-container{
  height: 100%;
}
</style>
